#include "stack.h"
#include "seqlist.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct _tag_StackNode _StackNode;
struct _tag_StackNode{
    SeqListNode node;
    void *data;
};

Stack* Stack_Create(){
    SeqList *seqList = SeqList_Create(50);
    return seqList;
}
void Stack_Destroy(Stack* stack){
    Stack_Clear(stack);
    SeqList_Destory(stack);
}
void Stack_Clear(Stack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return ;
    }
    while(SeqList_Length(stack)>0){
        Stack_Pop(stack);
    }
    SeqList_Clear(stack);
}
int Stack_Push(Stack* stack, void* item){
    if(stack==NULL){
        perror("stack can not be null");
        return -1;
    }
    _StackNode* sn=(_StackNode*)malloc(sizeof(_StackNode));
    sn->data=item;
    int code = SeqList_Insert((SeqList*)stack,(SeqListNode*)sn,SeqList_Length((SeqList*)stack));
    if(code!=0){
        if(sn!=NULL){
            free(sn);
        }
        return code;
    }
    return 0;
}
void* Stack_Pop(Stack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return NULL;
    }
    SeqListNode *last = SeqList_Delete((SeqList*)stack,SeqList_Length((SeqList*)stack)-1);
    if(last!=NULL){
        _StackNode* sn=(_StackNode*)last;
        void*d=sn->data;
        free(sn);
        return d;
    }
    return NULL;

}

void* Stack_Top(Stack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return NULL;
    }
    SeqListNode *last = SeqList_Get((SeqList*)stack,SeqList_Length((SeqList*)stack));
    if(last!=NULL){
        _StackNode* sn=(_StackNode*)last;
        return sn->data;
    }
    return NULL;
}
int Stack_Size(Stack* stack){
    if(stack==NULL){
        perror("stack can not be null");
        return -1;
    }
    return SeqList_Length((SeqList*)stack);
}
